import dataclasses
import struct
import crcmod

# modbus模式
crc16_fun = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)


@dataclasses.dataclass
class Frame:
    header: int  # 头: 2B
    payload_len: int  # 长度: 2B
    payload: bytes  # 动态长度二进制数据（长度由payload_len指定）
    crc16: int = 0  # 校验和:2B

    def to_bytes(self) -> bytes:
        data = struct.pack(
            f"<HH{self.payload_len}s", self.header, self.payload_len, self.payload
        )
        self.crc16 = crc16_fun(data)
        frame = data + struct.pack("<H", self.crc16)
        return frame


if __name__ == "__main__":
    data = [1,2,3,4]
    frame_a = Frame(0x7A5B, 4, bytes(data))
    print(frame_a.to_bytes())
